package com.example.group.network.express_plus_app;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.group.network.express_plus_app.Dao.AppDatabase;
import com.example.group.network.express_plus_app.Dao.UserDao.UserDao;
import com.example.group.network.express_plus_app.bean.MyResponse;
import com.example.group.network.express_plus_app.bean.User;
import com.example.group.network.express_plus_app.data.Result;
import com.example.group.network.express_plus_app.data.model.LoggedInUser;
import com.example.group.network.express_plus_app.http.GsonRequest;
import com.example.group.network.express_plus_app.http.MySingleton;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class SetDeliveryAddressActivity extends AppCompatActivity implements View.OnClickListener {
    RequestQueue queue;
    UserDao userDao;
    MainApplication application;
    EditText et_delivery_address;
    Button btn_update_delivery_address;
    LoggedInUser loggedInUser;
    String server_ip;
    String update_url;
    private final Gson gson = new Gson();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_delivery_address);
        setActionBar("更改常用收货地址");
        server_ip = getApplicationContext().getString(R.string.server_ip);
        update_url=server_ip+"express-user/user-controller/update-delivery-address?";
        userDao=AppDatabase.getsInstance(getApplication()).userDao();
        application=MainApplication.getInstance();
        queue= MySingleton.getInstance(getApplicationContext()).
                getRequestQueue();

        et_delivery_address=findViewById(R.id.et_delivery_address);
        btn_update_delivery_address=findViewById(R.id.btn_update_delivery_address);
        btn_update_delivery_address.setOnClickListener(this);
        initDeliveryAddress();

    }

    @Override
    public void onClick(View v) {

        if (v.getId()==R.id.btn_update_delivery_address){
            updateDeliveryAddress2();
        }
    }

    public void initDeliveryAddress(){

        loggedInUser = userDao.loadUserByPhone(application.mInfoMap.get("phone"));
        et_delivery_address.setText(loggedInUser.getDeliveryAddress());

    }

    public void updateDeliveryAddress(){
        String current_delivery_address = et_delivery_address.getText().toString();
        if (current_delivery_address.equals(loggedInUser.getDeliveryAddress())){
            Toast.makeText(this, "地址没有改变！", Toast.LENGTH_SHORT).show();
        }else {
            Map<String,String> head=new HashMap<>();
            head.put("Authorization","Bearer "+loggedInUser.getAccessToken());
            GsonRequest<MyResponse> userGsonRequest=new GsonRequest<MyResponse>(update_url, Request.Method.POST, MyResponse.class, head, new Response.Listener<MyResponse>() {
                @Override
                public void onResponse(MyResponse response) {
                    Log.i("收货地址",response.getStatusCode().toString());
                    if (response.getOk()){
                        //更新下数据库用户常用地址
                        loggedInUser.setDeliveryAddress(current_delivery_address);
                        Log.i("setting 收货地址",loggedInUser.toString());
                        //userDao.updateUserDeliveryAddress(loggedInUser);
                        Toast.makeText(application, "更新成功！", Toast.LENGTH_SHORT).show();

                    }else {
                        Toast.makeText(application, "网络更新失败！", Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("setting 收货地址","更新失败");
                    Toast.makeText(application, "更新失败！", Toast.LENGTH_SHORT).show();
                }
            }){
                @Override
                protected Map<String, String> getParams() {
                    Map<String,String> parms=new HashMap<>();
                    parms.put("userPhone",loggedInUser.getPhone());
                    parms.put("deliveryAddress",current_delivery_address);
                    return parms;
                }
            };
            userGsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(userGsonRequest);

        }
    }

    public void updateDeliveryAddress2(){
        String current_delivery_address = et_delivery_address.getText().toString();
        String update_url_2=server_ip+"express-user/user-controller/update-delivery-address?userPhone="+loggedInUser.getPhone()+"&deliveryAddress="+current_delivery_address;
        if (current_delivery_address.equals(loggedInUser.getDeliveryAddress())){
            Toast.makeText(this, "地址没有改变！", Toast.LENGTH_SHORT).show();
        }else {
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                    (Request.Method.POST, update_url_2, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            Log.i("修改快递地址",response.toString());
                            response.toString();
                            MyResponse myResponse = JSON.parseObject(response.toString(), MyResponse.class);

                            if (myResponse.getOk()){
                                //更新下数据库用户常用地址
                                loggedInUser.setDeliveryAddress(current_delivery_address);
                                Log.i("setting 收货地址",loggedInUser.toString());
                                userDao.updateUserDeliveryAddress(loggedInUser);
                                Toast.makeText(application, "更新成功！", Toast.LENGTH_SHORT).show();

                            }else {
                                Toast.makeText(application, "网络更新失败！", Toast.LENGTH_SHORT).show();
                            }
                            //tv_volley_data.setText(tv_volley_data.getText()+",Response: " + response.toString());
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO: Handle error
                            //tv_volley_data.setText("Response: 连接超时" + error.getNetworkTimeMs());
                        }
                    }){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> head=new HashMap<>();
                    head.put("Authorization","Bearer "+loggedInUser.getAccessToken());
                    return head;
                }
            };

            jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(6000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(jsonObjectRequest);

        }
    }

    public void setActionBar(String title){
        //标题栏设置
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        supportActionBar.setHomeAsUpIndicator(R.drawable.ic_baseline_arrow_back_ios_24);
        supportActionBar.setTitle(title);

    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}